package al.jdbc.DAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import al.jdbc.dpbridge.DataSource;
import al.jdbc.dpbridge.MySqlDataSource;
import alOmrane.jdbc.beans.Courrier_arrive;
import alOmrane.jdbc.beans.Envoyer_vers;
import alOmrane.jdbc.beans.Piece_jointe_arrive;

public class Envoyer_versDAO {
	private Connection db;
	@SuppressWarnings("unused")
	private DataSource ds;
	private OrganigrammeDAO odao = new OrganigrammeDAO(new MySqlDataSource("jdbc:mysql://localhost/gestion_courriers", "root"));
	private Courrier_arriveDAO cdao = new Courrier_arriveDAO(new MySqlDataSource("jdbc:mysql://localhost/gestion_courriers", "root"));
	private Statement sql;
	public Envoyer_versDAO(DataSource ds){
		db = ds.getConnection();
		this.ds = ds;
		try {
			sql = db.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public List<Envoyer_vers> findByCourrier(Courrier_arrive c){
		List<Envoyer_vers> pjs = new ArrayList<Envoyer_vers>();
		try {
			String query = "SELECT * FROM envoyer_vers WHERE id_courrier_arrive="+c.getId()+" ;";

			ResultSet rs = sql.executeQuery(query);
			while(rs.next()){
				Envoyer_vers ev = new Envoyer_vers(Integer.parseInt(rs.getString(1)),
						c, 
						odao.findById(Integer.parseInt(rs.getString(2))));
				pjs.add(ev);
			}
			return pjs;
		}catch(Exception ex){
			return null;
		}
	}
	public boolean insert(Envoyer_vers p){
		try{

			StringBuffer sb = new StringBuffer("INSERT INTO `gestion_courriers`.`envoyer_vers` (`id_organigramme`, `id_courrier_arrive`) VALUES " +
					"('"+p.getCode_niv().getId()+"', '"+p.getNum_courrier().getId()+"');");
			sql.executeUpdate(sb.toString());
			return true;
		}catch(Exception ex){
			ex.printStackTrace();
			return false;
		}
	}
	public boolean delete(int idCourrier){
		try{

			StringBuffer sb = new StringBuffer("DELETE FROM envoyer_vers "+
					"WHERE id_courrier_arrive="+idCourrier+" ;");
			sql.executeUpdate(sb.toString());
			return true;
		}catch(Exception ex){
			System.out.println(ex.getMessage());
			return false;
		}
	}
}
